package com.jerry.base.thread;

import lombok.extern.slf4j.Slf4j;

/**
 * Created with IntelliJ IDEA
 * User: Jerry
 * Date: 2024/2/21
 * Time: 21:15
 * Description:
 */
public class SynchronizedUsage {

    public static void main(String[] args) {
        Seller seller = new Seller();
        for (int i = 0; i < 4; i++) {
            new Thread(seller).start();
        }
    }

}

@Slf4j
class Seller implements Runnable {

    private int sum = 100;

    private boolean finished = false;

    @Override
    public void run() {
        while (!finished) {
            sell();
        }
    }

    private synchronized void sell() {
        if (sum <= 0) {
            log.info("售卖结束");
            finished = true;
            return;
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info("{} 卖出一张票，总票数还剩 {} 张", Thread.currentThread().getName(), --sum);
    }
}
